package com.funsport.controller.web;

import com.funsport.common.Result;
import com.funsport.entity.Permission;
import com.funsport.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 权限管理控制器
 */
@RestController
@RequestMapping("/web/permission")
public class WebPermissionController {
    
    @Autowired
    private PermissionService permissionService;
    
    /**
     * 获取所有权限（树形结构）
     */
    @GetMapping("/tree")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<List<Permission>> tree() {
        List<Permission> tree = permissionService.getTreeList();
        return Result.success(tree);
    }
    
    /**
     * 获取菜单权限（树形结构）
     */
    @GetMapping("/menu-tree")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<List<Permission>> menuTree() {
        List<Permission> tree = permissionService.getMenuTree();
        return Result.success(tree);
    }
    
    /**
     * 获取权限详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<Permission> getById(@PathVariable Long id) {
        Permission permission = permissionService.getById(id);
        if (permission == null) {
            return Result.error("权限不存在");
        }
        return Result.success(permission);
    }
    
    /**
     * 创建权限
     */
    @PostMapping
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<Permission> create(@RequestBody Permission permission) {
        permission.setStatus("active");
        Permission created = permissionService.create(permission);
        return Result.success(created);
    }
    
    /**
     * 更新权限
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<Permission> update(@PathVariable Long id, @RequestBody Permission permission) {
        Permission existing = permissionService.getById(id);
        if (existing == null) {
            return Result.error("权限不存在");
        }
        
        permission.setId(id);
        Permission updated = permissionService.update(permission);
        return Result.success(updated);
    }
    
    /**
     * 删除权限
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<Void> delete(@PathVariable Long id) {
        permissionService.delete(id);
        return Result.success();
    }
}

